﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using SmartParking.Bussiness;
using SmartParking.Data.Entities;
using ADEVSO.Util;

namespace SmartParking.Web
{
    public partial class Reservations : System.Web.UI.Page
    {
        private static String ColonesCurrency = "¢";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                (Master as Template).Title = "Reserve su Espacio";
                (Master as Template).ActiveMenuItem = "Reservations";
                LoadParkings();
                LoadParkingZones();
                DisplayPrice();
                LoadReservations();
                LoadStartHours();
            }
        }

        protected void LoadParkings()
        {
            ParkingManager.BindParkings(ref ddlPark);
        }

        protected void LoadParkingZones()
        {
            if (!String.IsNullOrEmpty(ddlPark.SelectedValue))
            {
                ParkingManager.BindParkingZones(ref ddlParkZone, Convert.ToInt32(ddlPark.SelectedValue));
            }
        }

        protected void DisplayPrice()
        {
            if (!String.IsNullOrEmpty(ddlParkZone.SelectedValue))
            {
                //TODO:
                //ParkingZoneFare parkingZoneWebFare = ParkingManager.GetParkingZoneWebFare(Convert.ToInt32(ddlParkZone.SelectedValue));
                //lbPrice.Text = String.Format("Precio/Hora: {0}{1} + {0}{2} (comisión)", ColonesCurrency, parkingZoneWebFare.PriceHour, parkingZoneWebFare.ParkingZone.WebCommisionAmount);
            }
        }

        protected void LoadStartHours()
        {
            if (!String.IsNullOrEmpty(ddlParkZone.SelectedValue))
            {
                ParkingZone parkingZone = ParkingManager.GetParkingZone(Convert.ToInt32(ddlParkZone.SelectedValue));
                List<Hour> hours = Hour.AM0100.RangeHours(parkingZone.OpenHour.ToHour(), parkingZone.CloseHour.ToHour(), parkingZone.AllowHalfHour);
                ddlStartHour.DataSource = hours;
                ddlStartHour.DataBind();
                hours.RemoveAt(0);
                LoadEndHours(hours);
            }
        }

        protected void LoadEndHours(List<Hour> hours = null)
        {
            if (!String.IsNullOrEmpty(ddlParkZone.SelectedValue))
            {
                if (hours == null && !String.IsNullOrEmpty(ddlStartHour.SelectedValue))
                {
                    ParkingZone parkingZone = ParkingManager.GetParkingZone(Convert.ToInt32(ddlParkZone.SelectedValue));
                    Hour startHour = ((Hour)(((int)ddlStartHour.SelectedValue.ToHour()) + 1));
                    hours = Hour.AM0100.RangeHours(startHour, parkingZone.CloseHour.ToHour(), parkingZone.AllowHalfHour);
                }
                ddlEndHour.DataSource = hours;
                ddlEndHour.DataBind();
            }
        }

        protected void LoadReservations()
        {
            List<OrderDetail> reservations = ReservationsManager.GetLiveReservations(Application, Session);
            grdReservations.DataSource = reservations;
            grdReservations.DataBind();
            cmdForward.Enabled = reservations.Count > 0;
        }

        protected String DisplayPark(Object IdParkZone)
        {
            ParkingZone parkingZone = ParkingManager.GetParkingZone(Convert.ToInt32(IdParkZone));
            return parkingZone.Parking.Name;
        }

        protected String DisplayParkZone(Object IdParkZone)
        {
            ParkingZone parkingZone = ParkingManager.GetParkingZone(Convert.ToInt32(IdParkZone));
            return parkingZone.Name;
        }

        protected String DisplayDay(Object date)
        {
            //return TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(date), (Master as Template).LocalTimeZone).ToString("dd/MM/yyyy");
            return Convert.ToDateTime(date).ToString("dd/MM/yyyy");
        }

        protected String DisplayHour(Object date)
        {
            //return TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(date), (Master as Template).LocalTimeZone).ToString("hh:mm tt");
            return Convert.ToDateTime(date).ToString("hh:mm tt");
        }

        protected String DisplayAmount(Object amount)
        {
            return ColonesCurrency + Convert.ToDecimal(amount).ToString();
        }

        protected String DisplayTotalAmount()
        {
            List<OrderDetail> reservations = ReservationsManager.GetLiveReservations(Application, Session);
            var TotalAmount =
                (from reservation in reservations
                 select reservation.Amount).Sum();
            return ColonesCurrency + Convert.ToDecimal(TotalAmount).ToString();
        }

        protected String DisplayCommission(Object amount)
        {
            return ColonesCurrency + Convert.ToDecimal(amount).ToString();
        }

        protected String DisplayTotalCommission()
        {
            List<OrderDetail> reservations = ReservationsManager.GetLiveReservations(Application, Session);
            var TotalCommission =
                (from reservation in reservations
                 select reservation.Commission).Sum();
            return ColonesCurrency + Convert.ToDecimal(TotalCommission).ToString();
        }

        protected void ddlPark_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadParkingZones();
        }

        protected void ddlParkZone_SelectedIndexChanged(object sender, EventArgs e)
        {
            DisplayPrice();
            LoadStartHours();
        }

        protected void ddlStartHour_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadEndHours();
        }

        protected void imgbtnValidate_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                OrderDetail reservation = FillReservation();
                if (ReservationsManager.VerifyReservation(Application, Session, reservation, true))
                    imgbtnReserve.Enabled = true;
            }
            catch (SmartParkingException ex)
            {
                // Show alert error
                Response.Write(String.Format("<script>window.alert('{0}');</script>", ex.Message));
            }
            catch (Exception ex)
            {
                // Show error page
            }
        }

        protected void imgbtnReserve_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                OrderDetail reservation = FillReservation();
                ReservationsManager.AddLiveReservation(Application, Session, Profile.ManagerID, reservation);
                imgbtnReserve.Enabled = false;
                
                ResetReservation();

                LoadReservations();
            }
            catch (SmartParkingException ex)
            {
                // Show alert error
                Response.Write(String.Format("<script>window.alert('{0}');</script>", ex.Message));
            }
            catch (Exception ex)
            {
                // Show error page
            }
        }

        private void ResetReservation()
        {
            ddlStartHour.SelectedIndex = 0;
            ddlEndHour.SelectedIndex = 0;
            tboxDate.Text = String.Empty;
            tboxCar.Text = String.Empty;
            imgbtnReserve.Enabled = false;
        }

        private OrderDetail FillReservation()
        {
            OrderDetail reservation = new OrderDetail();
            reservation.ParkingZoneID = Convert.ToInt32(ddlParkZone.SelectedValue);
            DateTime date = DateTime.ParseExact(tboxDate.Text, calDate.Format, null);
            Hour hour = ddlStartHour.Text.ToHour();
            TimeSpan time = new TimeSpan(hour.GetHour(), hour.GetMinutes(), 0);
            reservation.StartDateTime = date.Add(time);
            hour = ddlEndHour.Text.ToHour();
            time = new TimeSpan(hour.GetHour(), hour.GetMinutes(), 0);
            reservation.EndDateTime = date.Add(time);
            reservation.CarPlate = tboxCar.Text;
            return reservation;
        }

        #region grdReservations

        protected void grdReservations_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridViewRow insertRow = (sender as ADEVSO.Web.UI.WebControls.GridView).InsertRow;
            if (insertRow != null)
            {
                Label lb = e.Row.FindControl("lbIdPark") as Label;
                if (lb != null)
                    lb.Text = "-1";
            }
        }

        protected void grdReservations_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            ADEVSO.Web.UI.WebControls.GridView grid = sender as ADEVSO.Web.UI.WebControls.GridView;
            GridViewRow row = e.RowIndex == -1 ? grid.InsertRow : grid.Rows[e.RowIndex];

            //DAO.Park park = BLL.Parkings.New(Session, Request.UserHostAddress, Profile.ManagerID);
            //park.IdPark = Convert.ToInt32((row.FindControl("lbIdPark") as Label).Text);
            ////park.IdCustomer = Convert.ToInt32(cboxCustomer.SelectedValue);
            //park.Name = (row.FindControl("tboxName") as TextBox).Text;
            //park.BankAccountNumber = (row.FindControl("tboxBankAccountNumber") as TextBox).Text;
            //park.Save(park.IdPark);

            grdReservations.EditIndex = -1;
            LoadParkings();
        }

        #endregion
    }
}